package com.example.cc.mygit.view.language;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;

import com.example.cc.mygit.base.BaseRecyclerActivity;
import com.example.cc.mygit.model.Language;
import com.haibin.androidbase.activity.BaseRecyclerViewActivity;
import com.haibin.androidbase.adapter.BaseRecyclerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cc on 2016/12/3.
 */

public class LanguageActivity extends BaseRecyclerActivity<LanguageContract.Presenter, Language> implements LanguageContract.View {

    private ArrayList<Language> mLanguages;

    public static void show(Fragment fragment, ArrayList<Language> languages, int reqCode) {
        Intent intent = new Intent(fragment.getActivity(), LanguageActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("languages", languages);
        intent.putExtras(bundle);
        fragment.startActivityForResult(intent, reqCode);

    }

    @Override
    protected void initData() {
        mLanguages = (ArrayList<Language>) getBundle().getSerializable("languages");
        new LanguagePresenter(this).start();
        super.initData();
    }

    @Override
    public void onItemClick(int position, long itemId) {
        Language language = mAdapter.getItem(position);
        language.setAdd(!language.isAdd());
        mAdapter.updateItem(position);
        if (language.isAdd()) {
            mLanguages.add(language);
        } else {
            mLanguages.remove(language);
        }
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("languages", mLanguages);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        super.finish();
    }

    @Override
    public void onRefreshSuccess(List<Language> items) {
        for (Language l:items){
            for (Language language :mLanguages){
             if (l.isAdd())
                 continue;
                else
                 l.setAdd(l.getId() == language.getId());
            }
        }
        super.onRefreshSuccess(items);
    }

    @Override
    public void onLoadMore() {
        mAdapter.setFooterState(BaseRecyclerAdapter.FOOTER_STATE_NO_MORE,true);
    }

    @Override
    protected BaseRecyclerAdapter<Language> getAdapter() {
        return new LanguageAdapter(this);
    }
}
